/*cardDoctorAdmin - App.js - Yadong Zhu 2014*/
(function() {
    'use strict';
    var t = '?v0.3';
    // Declare app level module which depends on filters, and services
    var loadCardResolve={
        card:['$route','$q','cardDoctorAdminService',function($route,$q,cardDoctorAdminService){
            var deferred = $q.defer();
            if ($route.current.params.id){
                deferrec.resolve("xxx");
            } else {
                deferred.resolve(undefined);
            }
            return deferred.promise;

        }]
    };
    angular.module('cardDoctorAdmin', [
        'ngRoute',
        'ngSanitize',
        'cardDoctorAdmin.filters',
        'cardDoctorAdmin.services',
        'cardDoctorAdmin.directives',
        'cardDoctorAdmin.controllers',
        'ui.bootstrap',
        'pascalprecht.translate'
    ])
    //set global 
    .run(["$rootScope","$translate",function($rootScope,$translate) {
        $rootScope.lang=$translate.use();
         $rootScope.sendError = function sendError(err) {
            var cardString = JSON.stringify($rootScope.card);
            window.open('mailto:yadong.zhu@gmail.com?subject=Err&body=Error Report ' + escape("\n\n\n\n\n\n") + '-----Debug info-----' + escape("\n\n") + encodeURIComponent("xxx"));
        };     
        $rootScope.setLang=function(lang){
            $rootScope.lang=lang;
             $translate.use(lang);
        }
    }]).
    config(['$translateProvider',function ($translateProvider) {
        //load language json
          var $http = angular.injector(['ng']).get('$http');
          $http({method: 'GET', url: 'i18n/en_US.json'})
          .success(function(data){
            $translateProvider.translations('en_US', data);       
          })
          .error(function(err){
            console.error("loading en_US fails:"+err)
          })
          $http({method: 'GET', url: 'i18n/zh_CN.json'})
          .success(function(data){
            $translateProvider.translations('zh_CN', data);       
          })
          .error(function(err){
            console.error("loading zh_CN fails:"+err)
          })
          $translateProvider.preferredLanguage('en_US');
    }])
    .config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.when('/', {
                templateUrl: 'partials/card-search.html' + t,
                controller: 'searchCtrl',
                reloadOnSearch: false
            });

            $routeProvider.when('/card-admin', {
                redirectTo: '/card-admin/new'
            });
            $routeProvider.when('/card-admin/new', {
                templateUrl: 'partials/card-admin.html' + t,
                controller: 'cardAdminCtrl',
                resolve:loadCardResolve
            });

            $routeProvider.when('/card-admin/:id', {
                templateUrl: 'partials/card-admin.html' + t,
                controller: 'cardAdminCtrl',
                resolve:loadCardResolve
            });
            
            $routeProvider.when('/chat', {
                templateUrl: 'partials/chat.html' + t,
                controller: 'chatCtrl'
            });
            
            $routeProvider.when('/me', {
            	templateUrl: 'partials/me.html' + t,
            	controller: 'meCtrl'
            });
            
            $routeProvider.when('/discover', {
            	templateUrl: 'partials/discover.html' + t,
            	controller: 'discoverCtrl'
            });
            
            $routeProvider.when('/signup', {
            	templateUrl: 'partials/signup.html' + t,
            	controller: 'signupCtrl'
            });
            $routeProvider.when('/signin', {
            	templateUrl: 'partials/signin.html' + t,
            	controller: 'signinCtrl'
            });

            $routeProvider.otherwise({
                redirectTo: '/'
            });
        }
    ])
        .config(['$httpProvider',
            function($httpProvider) {
                $httpProvider.interceptors.push(['$q', '$injector',
                    function($q, $injector) {
                        var isLoggingIn = false;
                        return {
                            request: function(config) {
                                return config || $q.when(config);
                            },
                            responseError: function(response) {
                                window.console && console.log(response);
                                if (response.status === 403 || response.status === 412) {
                                    // redirect to URLs.login
                                    console.log("redirect to URLs.login");
                                    if (!isLoggingIn) {
                                        isLoggingIn = true;
                                        $injector.invoke(['$http', '$modal',
                                            function($http, $modal) {
                                                var modalInstance = $modal.open({
                                                    templateUrl: 'partials/loginModal.html',
                                                    controller: 'loginCtrl'
                                                });
                                                modalInstance.result.then(function() {
                                                    isLoggingIn = false;
                                                }, function() {
                                                    isLoggingIn = false;
                                                })['finally'](function() {
                                                    modalInstance = undefined;
                                                });
                                            }
                                        ]);
                                    }
                                }
                                console.log("Response -> " + response);
                                return $q.reject(response);
                            }
                        };
                    }
                ]);
            }
        ]);
}());

